<template>
    <div class="container">
        <div class="header-container-detail" v-show="isVisible">
            <el-form label-width="100px">
                <el-row class="backGC">
                    <el-col :span="23">
                        <div class="display-grid1">
                            <el-form-item label="条目编码">
                                <el-input v-model="staticResult.entryCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="条目名称">
                                <el-input v-model="staticResult.entryName" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <!-- <el-form-item label="外部下单编码">
                                <el-input v-model="staticResult.outOrderCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item> -->
                            <el-form-item label="触警类型">
                                <el-input v-model="thresholdType" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="计算日期">
                                <el-date-picker v-model="calculate" type="datetime" placeholder="选择日期时间" readonly size="mini"> </el-date-picker>
                            </el-form-item>
                        </div>
                        <div class="display-grid1">
                            <el-form-item label="计算结果">
                                <el-input v-model="staticResult.calculateValue" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="条目比较方向">
                                <el-input v-model="compareType" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="条目触发值">
                                <el-input v-model="staticResult.thresholdValue" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="1">
                        <div class="boxStyle" @click="rotateClick">
                            <span class="el-icon-arrow-down iconStyle" v-if="isOpen"></span>
                            <span class="el-icon-arrow-right iconStyle" v-else></span>
                        </div>
                    </el-col>
                </el-row>

                <el-row v-if="isOpen" class="opened-content">
                    <el-col :span="23">
                        <div class="display-grid1">
                            <el-form-item label="流水号">
                                <el-input v-model="staticResult.resultId" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="静态条目KEY">
                                <el-input v-model="staticResult.entryKey" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="产品代码">
                                <el-input v-model="fundCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="组合编码">
                                <el-input v-model="staticResult.fundAccountCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                        </div>
                        <div class="display-grid1">
                            <el-form-item label="分支序号">
                                <el-input v-model="staticResult.calBrNos" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="证券代码">
                                <el-input v-model="staticResult.stockCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="发行人代码">
                                <!-- <el-input v-model="staticResult.issueCode" placeholder="" readonly size="mini"></el-input> -->
                                <el-input v-model="computeIssueCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="银行代码">
                                <el-input v-model="bankCode" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                        </div>
                        <div class="display-grid2">
                            <el-form-item label="计算逻辑">
                                <el-input v-model="staticResult.calLogicShow" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                            <el-form-item label="错误信息">
                                <el-input v-model="staticResult.errorMessage" placeholder="" readonly size="mini"></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div :class="{ isCloseTableStyle: !isOpen, isOpenTableStyle: isOpen }">
            <vxe-table
                show-overflow
                border
                :expand-config="{ iconOpen: 'el-icon-remove', iconClose: 'el-icon-circle-plus', toggleMethod, visibleMethod: expandVisibleMethod }"
                ref="xTable"
                resizable
                auto-resize
                :data="dataSource"
                highlight-hover-row
                style="width: 100%"
                height="100%"
                v-loading="tableLoading"
            >
                <vxe-table-column type="expand" width="60px">
                    <template #content="{ row, rowIndex }">
                        <div class="expand-wrapper">
                            <span v-if="getDirectMode(row, rowIndex)" :key="key + rowIndex" style="font-size: 13px; font-weight: 700">{{
                                '计算模式:' + directModeTypes[getDirectMode(row, rowIndex)]
                            }}</span>

                            <div v-for="(value1, key1) in getData(row, rowIndex)" :key="key1 + rowIndex" style="margin: 2px 0">
                                <span style="font-size: 13px; font-weight: 700">{{ DATA_TYPE[key1] + ':' + numberFormat(value1) }}</span>
                                <el-popover placement="right" width="800" trigger="hover" @after-enter="handlePopoverShow">
                                    <!-- <div>
                                        <span style="font-weight: 700">统计表名：</span>
                                        {{ (dataBasic[rowIndex][key1] || {}).calculateTable }}&nbsp;
                                        {{
                                            '(' +
                                                ((
                                                    columnComments.find(
                                                        item => item.tableName === (dataBasic[rowIndex][key1] || {}).calculateTable
                                                    ) || {}
                                                ).tableComments || '') +
                                                ')' || {}
                                        }}
                                    </div>
                                    <div>
                                        <span style="font-weight: 700">统计主键：</span>
                                        {{ (dataBasic[rowIndex][key1] || {}).calculateTableKey }}&nbsp;
                                        {{
                                            getFieldName(
                                                columnComments.filter(item => item.tableName === (dataBasic[rowIndex][key1] || {}).calculateTable) ||
                                                    {},
                                                (dataBasic[rowIndex][key1] || {}).calculateTableKey,
                                                true
                                            )
                                        }}
                                    </div>
                                    <div>
                                        <span style="font-weight: 700">统计字段：</span>
                                        {{ (dataBasic[rowIndex][key1] || {}).calculateField }}&nbsp;
                                        {{
                                            getFieldName(
                                                columnComments.filter(item => item.tableName === (dataBasic[rowIndex][key1] || {}).calculateTable) ||
                                                    {},
                                                (dataBasic[rowIndex][key1] || {}).calculateField,
                                                true
                                            )
                                        }}
                                    </div> -->
                                    <risk-table
                                        :msg="{
                                            returnData: { list: dataDetails[rowIndex][key1] },
                                            dataKey: 'list',
                                            title: dnColumn[rowIndex][key1],
                                            checked: { on: false, option: false },
                                            hidePage: true,
                                            maxHeight: '200px',
                                        }"
                                        :key="listMsgNumKey + 'listMsgNumKey'"
                                        style="padding: 5px"
                                        v-loading="detailTableLoading"
                                    ></risk-table>
                                    <el-tag slot="reference" style="margin-left: 6px; cursor: default"> 详情 </el-tag>
                                </el-popover>
                            </div>
                        </div>
                    </template>
                </vxe-table-column>
                <vxe-table-column field="resultId" title="流水号" min-width="100"></vxe-table-column>
                <vxe-table-column field="entryCode" title="条目编码" min-width="100"></vxe-table-column>
                <vxe-table-column field="branchName" title="分支名称" min-width="100"></vxe-table-column>
                <vxe-table-column field="branchValue" title="分支值" min-width="120">
                    <template #default="{ row }">
                        <span>{{ numberFormatCIB(row.branchValue) || '--' }}</span>
                    </template>
                </vxe-table-column>
                <vxe-table-column field="branchNo" title="分支序号" min-width="120"></vxe-table-column>
                <vxe-table-column field="branchKey" title="静态分支KEY" min-width="120"></vxe-table-column>
            </vxe-table>
        </div>
    </div>
</template>
<script lang="ts">
import RiskTable from '@/common/components/risk-table.vue';
import DictionConstUtil from '@/utils/diction-const-util';
import { PrefixInteger, numberFormat, unitShow, numberFormatCIB } from '@/utils/tools';
import { Component, Vue, Prop } from 'vue-property-decorator';
import * as moment from 'moment';
import { getColumnComment } from '@/pages/risk-time/api';
@Component({
    name: 'InstReportDetail',
    components: {
        RiskTable,
    },
})
export default class InstReportDetail extends Vue {
    numberFormat = numberFormat;
    numberFormatCIB = numberFormatCIB;
    @Prop() staticResult: any;
    @Prop() history: boolean;
    @Prop({ default: true }) isVisible: boolean;

    private DATA_TYPE = {
        INSTRUCTION_STRICT: '不利方向值',
        INSTRUCTION_WIDE: '有利方向值',
        EARLY: '日初持仓值',
        INSTRUCTION_LENIENT: '指令从宽',
    };

    private directModeTypes = {
        '0': '有序从严控制',
        '1': '有序非从严控制',
        '2': '无序从严控制',
        '3': '无序非从严控制',
        '4': '有序从严控制(默认成交)',
        '5': '无序从严控制(默认成交)',
        '6': '有序从严控制(有利不显示)',
        '7': '无序从严控制(有利不显示)',
    };

    private isOpen: boolean = false; // 是否展开

    private thresholdType: string = ''; // 触警类型显示值

    private compareType: string = ''; // 条目比较方向显示值

    private fundCode: string = ''; // 产品代码显示值

    private calculate: string = ''; // 计算日期时间显示值

    private dataSource: any[] = []; // 表数据

    private bankCode: string = ''; // 银行代码

    private tableLoading: boolean = false; // 表数据加载

    private detailTableLoading: boolean = false; // 详情表数据加载

    private columns: any[] = []; // 表头结构信息

    private columnComments: any[] = []; // 字段说明

    private value: any[] = []; // 详情格式

    private dataDetails: any[] = []; // 实际参数和值

    private dataBasic: any[] = []; // 基础参数

    private dnColumn: any[] = []; // 详情列

    private listMsgNumKey: number = 0; // listMsg表数据渲染Key

    private directMode: string[] = []; // 计算模式

    private showValue: any[] = [];

    async mounted() {
        if (this.isVisible) {
            // 产品代码
            this.fundCode = await DictionConstUtil.FNFundShowCode(this.staticResult.fundCode);
            // 比较方向
            this.compareType = DictionConstUtil.CompareDirection[this.staticResult.compareType];
            // 触警类型
            this.thresholdType = DictionConstUtil.ThresholdType[this.staticResult.thresholdType];
            // 银行代码
            this.bankCode = this.staticResult.bankCode && this.staticResult.bankCode !== 'null' ? this.staticResult.bankCode : '';
            // 计算日期时间
            this.calculate = moment(
                this.staticResult.calculateDate + ' ' + PrefixInteger(this.staticResult.calculateTime, 6),
                'YYYYMMDD HHmmss'
            ).format('YYYY-MM-DD HH:mm:ss');
            let unit = this.staticResult.unit;
            this.staticResult.thresholdValue = numberFormatCIB(`${this.staticResult.thresholdValue || ''}`, unit, 'thresholdValue') + unitShow(unit);
            this.staticResult.calculateValue =
                numberFormatCIB(this.staticResult.calculateValue, unit == '无' || !unit ? 2 : unit) + unitShow(this.staticResult.unit);
        }

        this.getStaticBranchResult(this.staticResult.resultId);
    }

    get computeIssueCode() {
        return this.staticResult.issueCode == 'null' ? '空' : this.staticResult.issueCode;
    }

    toggleMethod({ expanded, row }) {
        if (expanded) {
            this.listMsgNumKey++;
        }
        return true;
    }

    expandVisibleMethod({ row }) {
        let data = JSON.parse(row.calculateDetails || '{}').dataDetails || {};
        if (data && Object.keys(data).length) {
            return true;
        }
        return false;
    }

    // 获取结果信息
    private getStaticBranchResult(resultId): void {
        this.dnColumn = [];
        this.tableLoading = true;
        let url;
        if (this.history) {
            url = '/instruction/inst/history/branch/result/' + resultId;
        } else {
            url = '/instruction/inst/branch/result/' + resultId;
        }

        // 历史指令分支结果
        this.$axios.get(url).then((res: any) => {
            let value = res || [];
            if (value) {
                value.forEach((item, i) => (item.key = item.branchKey + '-' + i));
                value.sort((a, b) => Number(a.branchNo) - Number(b.branchNo));
                this.dataSource = value;
                this.detailTableLoading = true;

                // 获取要查询的表的字段名
                let tableNames = [];
                let dt;
                this.dataSource.forEach(record => {
                    dt = JSON.parse(record.calculateDetails || '{}').dataBasic || {};
                    for (let key in dt) {
                        if (dt[key].calculateTable && !tableNames.includes(dt[key].calculateTable)) {
                            tableNames.push(dt[key].calculateTable);
                        }
                        // else if (!dt[key].calculateTable) {
                        //     console.log(dt);
                        // }
                    }
                });

                if (tableNames.length === 0) {
                    this.columnComments = [];
                    this.handleColumnInfo();
                    this.tableLoading = false;
                } else {
                    getColumnComment(tableNames).then(res => {
                        this.columnComments = res || [];
                        this.handleColumnInfo();
                    });
                }
            } else {
                this.tableLoading = false;
                this.dataSource = [];
            }
        });
    }

    /**
     * 处理字段信息
     * @private
     */
    private handleColumnInfo() {
        this.dataSource.forEach((record, rowIndex) => {
            let detail = JSON.parse(record.calculateDetails || '{}');
            // 基本格式
            this.dataBasic[rowIndex] = detail.dataBasic;

            // 获取所有统计主键
            let calculateTableKey = [];
            for (const key in this.dataBasic[rowIndex]) {
                if (this.dataBasic[rowIndex][key] && this.dataBasic[rowIndex][key]['calculateTableKey']) {
                    calculateTableKey.push(this.dataBasic[rowIndex][key]['calculateTableKey']);
                }
            }
            // 实际格式内容和数据
            this.dataDetails[rowIndex] = detail.dataDetails;
            // 计算模式
            this.directMode[rowIndex] = detail.directMode;

            // 大致格式名与值
            this.value[rowIndex] = JSON.parse(record.branchCalulateTypeResults || '{}');
            let col = JSON.parse(JSON.stringify({}));
            for (let key in detail.dataBasic) {
                // 中文字段信息条
                let columnInfo = this.columnComments.filter(item => item.tableName === (this.dataBasic[rowIndex][key] || {}).calculateTable) || {};
                this.$set(col, key, []);
                if (this.dataDetails[rowIndex][key]) {
                    // 获取表单字段中文名(dn为对应的英文字段)
                    for (let dn in this.dataDetails[rowIndex][key][0]) {
                        let needData = {
                            name: this.getFieldName(columnInfo, dn, false),
                            val: dn, // 英文字段
                            key: key,
                            minWidth: 100,
                            type: 'func',
                            funcBody: (value, row, val) =>
                                value != undefined && !calculateTableKey.includes(val) && val.toString().substr(0, 2) == 'N_'
                                    ? numberFormat(value, 2)
                                    : value || '--',
                        };
                        for (const objKey in needData) {
                            if (needData[objKey] === 'C_DATA_TYPE') {
                                needData['funcBody'] = function format(value: any) {
                                    if (value == '0') {
                                        return '持仓';
                                    } else {
                                        return '指令';
                                    }
                                };
                            }
                        }
                        col[key].push(needData);
                    }
                }
            }
            this.dnColumn.push(col);
            this.detailTableLoading = false;
            this.tableLoading = false;
        });
    }

    // 字段名称获取
    private getFieldName(fieldComments, fieldName, action): string {
        switch (fieldName) {
            case 'C_FUND_NAME_ST':
                return '基金简称';
            case 'C_STOCK_NAME_ST':
                return '证券简称';
            case 'C_DATA_TYPE':
                return '类型';
            case 'C_FD_AC_NAME':
                return '组合名称';
            case 'C_ASSET_NAME':
                return '资产单元名称';
            case 'C_SIMULATE_MESSAGE':
                return '信息来源';
            case 'N_DEAL_MARKET_VALUE47':
                return '基金现金资产（成交）';
            case 'N_MARKET_VALUE47':
                return '基金现金资产';
            default:
                break;
        }
        if (!fieldComments || !fieldName) {
            return '';
        }
        let fieldComment = (fieldComments.find(item3 => fieldName === item3.columnName) || {}).comments || '';
        if (action && fieldComment) {
            return '(' + fieldComment + ')';
        } else {
            return fieldComment;
        }
    }

    // 获取主表数据中的一条
    private getData(record, rowIndex): any {
        return this.value[rowIndex];
    }

    // 获取计算模式
    private getDirectMode(record, rowIndex): any {
        return this.directMode[rowIndex];
    }

    private handlePopoverShow() {
        this.listMsgNumKey++;
    }

    // // 详情
    // private getListMsg(key: string, rowIndex: number): any {
    //     let title = this.dnColumn[rowIndex][key];
    //     let list = this.dataDetails[rowIndex][key];
    //     console.log(list, '显示数据list');

    //     return {
    //         returnData: { list: list },
    //         dataKey: 'list',
    //         title: title,
    //         checked: { on: false, option: false },
    //         hidePage: true,
    //         maxHeight: '300px',
    //     };
    // }

    // 是否展开
    private rotateClick(): void {
        this.isOpen = !this.isOpen;
    }
}
</script>
<style lang="scss" scoped>
.container {
    .header-container-detail {
        border: 1px solid #ccc;
        margin-bottom: 10px;
    }
    .display-grid1 {
        display: grid;
        grid-template-columns: 25% 25% 25% 25%;
        height: 40px;
    }
    .display-grid2 {
        display: grid;
        grid-template-columns: 50% 50%;
        height: 40px;
    }
    .backGC {
        border: 1px solid #ccc;
        background-color: #f7f7f7;
    }
    .opened-content {
        // margin-top: 5px;
        // border: 1px solid #ccc;
        background-color: #f7f7f7;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
        width: 100% !important;
    }
    .boxStyle {
        margin: 40px 0 0 10px;
        width: 40px;
        height: 40px;
    }
    .iconStyle {
        color: #939398;
        font-size: 22px;
    }
}

/deep/ .vxe-table--render-default .vxe-body--expanded-cell {
    background-color: #d8e5f3;
    margin-left: 60px;
    padding: 3px;
}

/deep/ .vxe-table--body-wrapper {
    // overflow-x: hidden;
    height: fit-content !important;
}

/deep/ .el-tag {
    font-size: 12px;
    font-weight: 700;
    height: 26px;
    line-height: 26px;
}
// 隐藏部分搜索条件
.isCloseTableStyle /deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
    height: calc(100vh - 230px) !important;
}
// 显示部分搜索条件
.isOpenTableStyle /deep/ .vxe-table .vxe-table--body-wrapper.body--wrapper {
    height: calc(100vh - 350px) !important;
}
</style>
